package cn.cxyxj.client_app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Controller
public class HelloController {

    @Autowired
    RestTemplate restTemplate;


    @GetMapping("/codeLogin")
    public String hello(String code, Model model) {
        if (code != null) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("code", code);
            map.add("client_id", "client-a");
            map.add("client_secret", "123456");
            map.add("redirect_uri", "http://localhost:8091/codeLogin");
            map.add("grant_type", "authorization_code");
            String resp = restTemplate.postForObject("http://localhost:8091/oauth/token", map, String.class);
            JSONObject tokenResult = JSON.parseObject(resp);

            String access_token = tokenResult.getString("access_token");

            System.out.println(access_token);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + access_token);
            HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
            ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8082/user/get-current-user", HttpMethod.GET, httpEntity, String.class);
            String body = entity.getBody();

            // 根据用户信息生成局部 token
            return null;
        }
        return "index";
    }
}